$(function () {
    var queryUrl = '../deviceinfo/list';
    var devId = getQueryString('devId');
    if (devId) {
        queryUrl += '?devId=' + devId;
    }
    $("#jqGrid").Grid({
        url: queryUrl,
        sortname: 'CREATE_DATE',
        sortorder: 'DESC',
        rownumWidth: 35,
        height: 500,
        colModel: [
            {label: '设备编码', name: 'devCode', index: 'DEV_CODE', width: 110},
            {label: '设备名称', name: 'devName', index: 'DEV_NAME', width: 120},
            {label: '大类', name: 'devTypeBName', index: 'devTypeBName', width: 100},
            {label: '中类', name: 'devTypeMName', index: 'devTypeMName', width: 100},
            {label: '小类', name: 'devTypeSName', index: 'devTypeSName', width: 100},
            {label: '小类', name: 'devTypeS', hidden: true},
            {label: '生产线名称', name: 'devProductName', index: 'DEV_PRODUCT_NAME', width: 130},
            {label: '工序名称', name: 'devProceName', index: 'DEV_PROCE_NAME', width: 100},
            {label: '供应厂家名称', name: 'devSupplyName', index: 'devSupplyName', width: 120},
            {
                label: '设备状态', name: 'devStatus', index: 'DEV_STATUS', width: 80,
                formatter: function (v) {
                    return sysEnums.STATUS[v];
                }
            },
            {label: '', name: 'reserve4', index: 'RESERVE_4', width: 80, hidden: true},
            {label: '', name: 'nameplateUrl', width: 80, hidden: true},
            {
                label: '审核状态', name: '', index: '', width: 80,
                formatter: function (value, options, row) {
                    var reserve4 = row.reserve4;
                    return sysEnums.CHECK_FLAG[reserve4];
                }
            },
            {name: 'nameplate', hidden: true},
            {name: 'devKind', hidden: true},
            {label: 'id', name: 'id',  key: true, hidden: true},
            {
                label: '备件', width: 50, align: 'center', sortable: false,
                formatter: function (value, col, row) {
                    return "<button title='备件' class='btn btn-outline btn-info' onclick='vm.addReplace(\"" + row.id + "\")'><i class='fa fa-plus-circle'></i></button>";
                }
            },
            {
                label: '铭牌', width: 60, align: 'center', sortable: false,
                formatter: function (value, col, row) {
                    return "<button title='查看' class='btn btn-outline btn-info' onclick='vm.showQrCode(\"" + row.id + "\",\"" + row.nameplate + "\")'><i class='fa fa-qrcode'></i></button>";
                }
            },
            {
                label: '设备详情', width: 60, align: 'center', sortable: false,
                formatter: function (value, col, row) {
                    return "<button title='设备详情' class='btn btn-outline btn-info' onclick='vm.goDevDetail(\"" + row.id + "\", \"" + row.devCode + "\",\"" + row.devName + "\",\"" + row.devTypeS + "\",\"" + row.firmNo + "\")'><i class='fa fa-file-text-o'></i></button>";
                }
            }

        ]
    });
    vm.getRoleList();
    vm.getDevTypeB();
    vm.getTreeList();
    vm.getStore();
});
var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    },
    callback: {
        beforeCheck: true
    }

};
//设备组织树
var deptSetting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl",
            name: "complexName"
        }
    },
    callback: {
        beforeCheck: true,
        beforeClick: outTreeCheck
    }
};

function outTreeCheck(e, treeObj, treeNode) {
    vm.q.deptCode = treeObj.deptId;
    vm.query();
}

var vm = new Vue({
    el: '#rrapp',
    data: {
        isPrivilege: 0, // 是否是特权
        showList: true,
        title: null,
        deviceInfo: {
            devCode: '',
            devProductCode: '',
            devTypeB: '',//大类
            devTypeM: '',//中类
            devTypeS: '',//小类
            devSupply: '',//供应厂家
            isModuleRelated: '0',
            devKind: '1'
        },
        ruleValidate: {
            devName: [
                {required: true, message: '设备名称不能为空！', trigger: 'blur'}
            ],
            devProceName: [
                {required: true, message: '工序必选！', trigger: 'change'}
            ],
            devSupply: [
                {required: true, message: '供应厂家必选！', trigger: 'change'}
            ],
            devTypeB: [
                {required: true, message: '设备大类必选！', trigger: 'blur'}
            ],
            devTypeM: [
                {required: true, message: '设备中类必选！', trigger: 'blur'}
            ],
            devTypeS: [
                {required: true, message: '设备小类必选！', trigger: 'blur'}
            ]
        },
        q: {
            devCode: '',
            devProductCode: '', //左边的树
            deptCode: '', // 设备组织ID
            devTypeB: '',//大类
            devTypeM: '',//中类
            devTypeS: '',//小类
            devName: '',
            reserve4: '' ,// 审核状态
            erpCode:'',//erp编码
        },
        facType: '', //厂家名称
        devTypeBList: [], //大类
        devTypeMList: [], //中类
        devTypeSList: [],//小类
        devChangeRecord: {
            isDel: '',
            checkReason: '',
            checkResult: '',
            checkDate: '',
            isSpec: '',
            autoNo: '',
            useDept: '',
            devProceName: '',
            devProceNo: '',
            devProductName: '',
            devStatus: '1',
            devCode: '',
            devName: '',
            id: '',
            updateDate: '',
            updateUser: '',
            createUser: '',
            createDate: '',
            devSupply: '', // 供应厂商编码
            devSupplyName: '' // 供应厂商名称
        },
        treeList: [],
        devStatusList: enumsToList("STATUS"),
        devStatusList2: enumsToList("STATUS2"),
        picUrl: '',
        picUrl2: '',
        devFile: [],
        deviceList: [],
        showCheck: true,
        approveDeviceList: [], // 审核设备名称列表，审核窗口展示用
        approveParam: {
            approveDeviceIdList: [],
            status: '1',
            remark: ''
        },
        statusList: enumsToList('APPVAL_STATUS') // 审核状态
    },
    methods: {
        getRoleList: function () {
            Ajax.request({
                url: '../sys/user/isPrivilege',
                async: false,
                successCallback: function (r) {
                    vm.isPrivilege = r.isPrivilege;
                }
            });
        },
        loadFacType: function () {
            openWindow({
                type: 2,
                title: '<i class"=fa fa-file-text-o"></i> 选择厂家',
                content: '../sys/factorytype_choose.html?type=0',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getFacType();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        layer.close(index);
                        vm.deviceInfo.supplierId = res.id;
                        vm.deviceInfo.devSupply = res.faCode;
                        vm.deviceInfo.devSupplyName = res.faName;
                    }
                }
            })
        },
        //设备闲置记录
        addLeave: function () {
            var dev = getSelectedRowData("#jqGrid");
            var code = dev.devCode;
            var devName = dev.devName;
            var devId = dev.devId;
            if (code == null) {
                return;
            }
            openWindow({
                type: 2,
                title: '<i class="fa fa-bars"></i> 设备闲置记录',
                content: '../sys/devleaverecord.html?devCode=' + code + '&devName=' + devName + '&devId=' + devId
            });
        },
        // 导出设备基础信息
        exportData: function () {
            // 查询条件数组
            let queryConditionArray = [];
            if (this.q.devCode) {
                queryConditionArray.push('devCode=' + this.q.devCode);
            }
            if (this.q.devProductCode) {
                queryConditionArray.push('devProductCode=' + this.q.devProductCode);
            }
            if (this.q.deptCode) {
                queryConditionArray.push('deptCode=' + this.q.deptCode);
            }
            if (this.q.devTypeB) {
                queryConditionArray.push('devTypeB=' + this.q.devTypeB);
            }
            if (this.q.devTypeM) {
                queryConditionArray.push('devTypeM=' + this.q.devTypeM);
            }
            if (this.q.devTypeS) {
                queryConditionArray.push('devTypeS=' + this.q.devTypeS);
            }
            if (this.q.devName) {
                queryConditionArray.push('devName=' + this.q.devName);
            }
            if (this.q.reserve4) {
                queryConditionArray.push('reserve4=' + this.q.reserve4);
            }
            window.open('../deviceinfo/exportData?' + queryConditionArray.join('&'), '_blank');
        },
        exportWord: function () {
            // 查询条件数组
            let exportParam = {};
            if (this.q.devCode) {
                exportParam.devCode = this.q.devCode;
            }
            if (this.q.devProductCode) {
                exportParam.devProductCode = this.q.devProductCode;
            }
            if (this.q.deptCode) {
                exportParam.deptCode = this.q.deptCode;
            }
            if (this.q.devTypeB) {
                exportParam.devTypeB = this.q.devTypeB;
            }
            if (this.q.devTypeM) {
                exportParam.devTypeM = this.q.devTypeM;
            }
            if (this.q.devTypeS) {
                exportParam.devTypeS = this.q.devTypeS;
            }
            if (this.q.devName) {
                exportParam.devName = this.q.devName;
            }
            if (this.q.reserve4) {
                exportParam.reserve4 = this.q.reserve4;
            }
            exportFiles('#jqGrid', '../deviceinfo/export', exportParam);
        },
        generateQrCode: function () {
            // 查询条件数组
            let exportParam = {};
            if (this.q.devCode) {
                exportParam.devCode = this.q.devCode;
            }
            if (this.q.devProductCode) {
                exportParam.devProductCode = this.q.devProductCode;
            }
            if (this.q.deptCode) {
                exportParam.deptCode = this.q.deptCode;
            }
            if (this.q.devTypeB) {
                exportParam.devTypeB = this.q.devTypeB;
            }
            if (this.q.devTypeM) {
                exportParam.devTypeM = this.q.devTypeM;
            }
            if (this.q.devTypeS) {
                exportParam.devTypeS = this.q.devTypeS;
            }
            if (this.q.devName) {
                exportParam.devName = this.q.devName;
            }
            if (this.q.reserve4) {
                exportParam.reserve4 = this.q.reserve4;
            }
            Ajax.request({
                url: '../deviceinfo/generateQrCode',
                type: 'POST',
                params: exportParam,
                async: false,
                successCallback: function (r) {
                    alert(r.message, function () {
                        vm.reload();
                    });
                }
            })
        },
        //生产设备台账
        addChange: function () {
            var dev = getSelectedRowData("#jqGrid");
            var code = dev.devCode;
            if (code == null) {
                return;
            }
            openWindow({
                type: 2,
                title: '<i class="fa fa-bars"></i> 生产设备台账',
                content: '../sys/devchangerecord.html?devCode=' + code
            });
        },
        // 查看设备档案资料
        addEqu: function () {
            var selectedRowData = getSelectedRowData("#jqGrid");
            if (!selectedRowData) {
                return;
            }
            openWindow({
                type: 2,
                title: '<i class="fa fa-bars"></i> 设备档案',
                content: '../sys/ermsfile.html?moduleType=' + selectedRowData.devKind + '&id=' + selectedRowData.id
            })
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.picUrl = '';
            vm.picUrl2 = '';
            vm.deviceInfo = {
                id: '',
                isModuleRelated: '0',
                devKind: '1',
                delFlag: 1,
                moreFirmNo: 0,
                devProductCode: '',
                devProductName: '',
                url: '',
                nowCheckDate: new Date(),
                checkCycle: '',
                reserve_4: '0',
                devProceNo: '',
                devProceName: '',
                devSupply: '', // 供应厂商编码
                devSupplyName: '' // 供应厂商名称
            };
            vm.getTree();
        },
        update: function (event) {
            var id = getSelectedRows("#jqGrid");
            if (id == null) {
                return;
            }
            var result = getSelectedRowData("#jqGrid");
            // 特权人员可以修改审批过的数据
            if (vm.isPrivilege == 0) {
                if (result.reserve4 == 1) {
                    alert("当前审批已经通过，禁止更改！");
                    return;
                }
            }
            vm.showList = false;
            vm.title = "修改";
            vm.getInfo(id);
            vm.getTree();
            vm.getDevFile(id)
        },
        saveOrUpdate: function (event) {
            // 构建URL
            var url = '../deviceinfo';
            url += (vm.deviceInfo.id == (null || '')) ? '/save' : '/update';
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.deviceInfo),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            var titleConten = '确定要删除选中的记录？';
            if (ids == null) {
                return;
            }
            var result = getSelectedRowData("#jqGrid");
            // 特权人员可以修改审批过的数据
            if (vm.isPrivilege == 0) {
                if (result.reserve4 == 1) {
                    alert("当前审批已经通过，禁止更改！");
                    return;
                }
            }
            /*
           * 1.先请求接口，把数据拼接到完成了在加载
           * */
            vm.getInfo(ids);
            $.ajax({
                url:'../deviceinfo/loadDevAssociationStat?devId='+result.id,
                type: "GET",
                async: true,
                success: function (res) {
                    if(res.msg){
                         titleConten ="检测到当前设备已有 [ " +res.msg + " ]，是否确认删除？"
                    }
                    layer.confirm(titleConten,{icon: 7,title:'删除确认提示'},function (){
                        Ajax.request({
                            url: "../deviceinfo/delete",
                            params: JSON.stringify(ids),
                            type: "delete",
                            contentType: "application/json",
                            successCallback: function (r) {
                                alert('操作成功', function (index) {
                                    vm.reload();
                                });
                            }
                        });
                    })
                }
            })
        },
        getInfo: function (id) {
            let _this = this;
            Ajax.request({
                url: "../deviceinfo/info/" + id,
                async: true,
                successCallback: function (r) {
                    if(r.deviceInfo.devTypeB){
                        _this.getDevTypeM(r.deviceInfo.devTypeB)
                    }
                    if(r.deviceInfo.devTypeM){
                        _this.getDevTypeS(r.deviceInfo.devTypeM)
                    }
                    vm.deviceInfo = r.deviceInfo;
                    console.log(vm.deviceInfo,'zheli')
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                search: true,
                postData: {
                    'devCode': vm.q.devCode,
                    'deptCode': vm.q.deptCode,
                    'devName': vm.q.devName,
                    'devProductCode': vm.q.devProductCode,
                    'devTypeB': vm.q.devTypeB,
                    'devTypeM': vm.q.devTypeM,
                    'devTypeS': vm.q.devTypeS,
                    'faCode': vm.q.faCode,
                    'faName': vm.q.faName,
                    'reserve4': vm.q.reserve4
                },
                page: page
            }).trigger("reloadGrid", [{page: 1}]);
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            vm.q = {
                devCode: '',
                devProductCode: '',
                devTypeB: '',//大类
                devTypeM: '',//中类
                devTypeS: '',//小类
                faCode: '',//供应厂家编码
                faName: '',//供应厂家名称
                devName: '',
                reserve4: '',
                deptCode: ''
            };
            deptZtree.cancelSelectedNode();
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        choose: function (typeB) {
            vm.showCheck = true;
            if (typeB.typeCode !== '1010') {
                vm.showCheck = false;
            }
        },
        getDevTypeB: function () {
            Ajax.request({
                url: "../devtype/queryAll",
                params: {typeTp: 2},
                async: true,
                successCallback: function (r) {
                    vm.devTypeBList = r.list;
                }
            });
        },
        getDevTypeM: function (id) {
            if (id) {
                Ajax.request({
                    url: "../devtype/queryAll",
                    params: {typePid: id, typeTp: 1},
                    async: true,
                    successCallback: function (r) {
                        vm.devTypeMList = r.list;
                    }
                });
            }
        },
        getDevTypeS: function (id) {
            if (id) {
                Ajax.request({
                    url: "../devtype/queryAll",
                    params: {typePid: id, typeTp: 0},
                    async: true,
                    successCallback: function (r) {
                        vm.devTypeSList = r.list;
                    }
                });
            }
        },
        //设备信息返填
        getDevCodeName: function (id) {
            Ajax.request({
                url: "../deviceinfo/info/" + id,
                type: 'POST',
                successCallback: function (r) {
                    if (r.deviceInfo) {
                        vm.devChangeRecord.devName = r.deviceInfo.devName
                        vm.devChangeRecord.devProductName = r.deviceInfo.devProductName    //生产线名称 devProductName
                        vm.devChangeRecord.devProceNo = r.deviceInfo.devProceNo   //工序号 devProceNo
                        vm.devChangeRecord.devProceName = r.deviceInfo.devProceName  //工序名称 devProceName
                        vm.devChangeRecord.devCode = r.deviceInfo.devCode//设备编号
                        vm.devChangeRecord.autoNo = r.deviceInfo.autoNo//自编号
                        if (r.deviceInfo.devStatus) {
                            vm.devChangeRecord.devStatus = parseInt(r.deviceInfo.devStatus)//设备状态
                        }
                        vm.devChangeRecord.checkDate = r.deviceInfo.checkDate//验收日期
                        // vm.devChangeRecord.isSpec = r.deviceInfo.devKind//特种设备
                    }
                }
            });
        },
        //设备变更 每个设备只有设备变更一条记录  如果存在就更新 否则新增
        changeStatus: function () {
            var row = getSelectedRowData("#jqGrid");
            var ids = row.id;
            var devUrl = '';
            if (ids == null) {
                return;
            }
            vm.getDevCodeName(ids)
            openWindow({
                title: "设备变更",
                area: ['750px', '550px'],
                content: jQuery("#changeLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    /*  //根据devCode查询数据是否存在
                      Ajax.request({
                          url: "../devchangerecord/getInfoByDevCode/" + row.devCode,
                          type: 'POST',
                          successCallback: function (res) {
                              console.log(res)
                              if (res.devChangeRecord) {
                                  devUrl = "../devchangerecord/update"
                              } else {
                                  devUrl = "../devchangerecord/save"
                              }
                          }
                      });
                      console.log(devUrl)*/
                    //设备变更操作
                    Ajax.request({
                        url: "../devchangerecord/infoChange",
                        params: JSON.stringify(vm.devChangeRecord),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            layer.close(index);
                            alert('操作成功', function (index) {
                                vm.reload();
                            });
                        }
                    });
                }
            });
        },
        goMoreFirmNo: function () {
            if (vm.deviceInfo.id) {
                openWindow({
                    type: 2,
                    title: '<i class="fa fa-audio-description"></i> 固资编号',
                    content: '../sys/devsolidcapital.html?id=' + vm.deviceInfo.id
                })
            } else {
                if (!vm.deviceInfo.devTypeB) {
                    alert("设备大类不能为空");
                    return;
                }
                var total = 0;
                Ajax.request({
                    url: "../deviceinfo/countByDevTypeB",
                    params: {devTypeB: vm.deviceInfo.devTypeB},
                    async: false,
                    successCallback: function (r) {
                        total = r.total + 1;
                        vm.deviceInfo.devCode = 'CQA-' + vm.deviceInfo.devTypeB + '-' + (Array(5).join(0) + total).slice(-5);
                    }
                });
                Ajax.request({
                    url: "../deviceinfo/save",
                    params: JSON.stringify(vm.deviceInfo),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function (r) {
                        vm.deviceInfo.id = r.id;
                        openWindow({
                            type: 2,
                            title: '<i class="fa fa-audio-description"></i> 固资编号',
                            content: '../sys/devsolidcapital.html?id=' + r.id
                        })
                    }
                });
            }
        },
        goDevSpecial: function (id) {
            openWindow({
                type: 2,
                title: '<i class="fa fa-anchor"></i> 添加工位',
                content: '../sys/devspecialworstation.html?id=' + id
            })
        },
        addReplace: function (id) {
            openWindow({
                type: 2,
                area: ['100%', '100%'],
                title: '<i class="fa fa-plus-circle"></i> 添加备件',
                content: '../sys/devAddReplace.html?id=' + id
            })
        },
        goDevDetail: function (devId, devCode, devName, devTypeS, firmNo) {
            openWindow({
                type: 2,
                area: ['100%', '100%'],
                title: '<i class="fa fa-bars"></i> 设备详情',
                content: '../sys/devdetail.html?devId=' + devId + '&devCode=' + devCode + '&devName=' + encodeURI(encodeURI(devName)) + '&devTypeS=' + devTypeS + '&firmNo=' + firmNo
            })
        },
        showQrCode: function (devId,nameplate) {
            var paramArray = ["devId=" + devId];
            if(nameplate && nameplate != 'null' & nameplate != 'undefined' ){
                paramArray.push("nameplate=" + nameplate);
            }
            openWindow({
                type: 2,
                area: ['50%', '65%'],
                title: '<i class="fa fa-bars"></i> 设备铭牌',
                content: '../sys/qrcode.html?'+paramArray.join('&')
            });
        },
        getTreeList: function () {
            Ajax.request({
                url: '../sys/user/treeDeptBySCX',
                async: false,
                successCallback: function (r) {
                    vm.treeList = r.list;
                }
            });
        },
        //加载列表页树
        getStore: function () {
            deptZtree = $.fn.zTree.init($("#storeTree"), deptSetting, vm.treeList);
            // 默认展开工厂一级
            deptZtree.expandNode(deptZtree.getNodeByParam("deptId",'01',null));
            //deptZtree.expandAll(true);
        },
        getTree: function () {
            //加载分类树
            ztree = $.fn.zTree.init($("#categoryTree"), setting, vm.treeList);
            // 默认展开工厂一级
            ztree.expandNode(ztree.getNodeByParam("deptId",'01',null));
            var node = ztree.getNodeByParam("deptId", vm.deviceInfo.devProductCode);
            if (node) {
                ztree.selectNode(node);
                vm.deviceInfo.devProductName = node.name;
            } else {
                node = ztree.getNodeByParam("deptId", "01");
                ztree.selectNode(node);
            }
        },
        deptTree: function (param) {
            openWindow({
                title: "选择工序",
                area: ['300px', '450px'],
                content: jQuery("#categoryLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    if (node[0].deptType === 'DT_CJKSCX') {
                        if (node[0].deptId.length > 6) {
                            // 设置设备所在组织部门
                            vm.deviceInfo.deptCode = node[0].deptId;
                            // 设置工序名称和编码
                            vm.deviceInfo.devProceNo = node[0].dcode;
                            vm.deviceInfo.devProceName = node[0].name;
                            // 设置产线名称和编码
                            vm.deviceInfo.devProductCode = node[0].parentCode;
                            vm.deviceInfo.devProductName = node[0].parentName;
                            layer.close(index);
                        } else {
                            alert("请选择工序");
                        }
                    } else {
                        alert("请选择工序");
                    }
                }
            });
        },
        devCodeIcc: function () {
            var row = getSelectedRowData("#jqGrid");
            var id = row.id;
            if (id == null) {
                return;
            }
            openWindow({
                type: 2,
                title: '<i class="fa fa-list-ol"></i> ICC代码维护',
                content: '../device/devcodeicc.html?id=' + id + '&devCode=' + row.devCode + '&devName=' + encodeURI(encodeURI(row.devName))
            })
        },
        devfile: function () {
            var row = getSelectedRowData("#jqGrid");
            var id = row.id;
            if (id == null) {
                return;
            }
            openWindow({
                type: 2,
                title: '<i class="fa fa-list-ol"></i> 设备图片',
                content: '../device/devfile.html?devId=' + id
            })
        },
        //查询设备图片
        getDevFile: function (devId) {
            if (devId) {
                Ajax.request({
                    url: "../devfile/queryAll?fileType=" + 1 + '&devId=' + devId,
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function (r) {
                        if (r.list.length > 0) {
                            vm.deviceInfo.url = r.list[0].url;
                            var url = vm.deviceInfo.url;
                            picUrl2 = r.list[0].url;
                            if (url) vm.picUrl = url.substring((url.lastIndexOf("\/") + 1), url.length);
                        }

                    }
                });
            }
        },
        handleError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传格式正确的图片。'
            });
        },
        handleMaxSize: function (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
            });
        },
        handleSuccess: function (res, file) {
            this.$Loading.finish();
            iview.Message.success('文件上传成功');
            vm.deviceInfo.url = file.response.url;
            var url = vm.deviceInfo.url;
            picUrl2 = vm.deviceInfo.url;
            if (url) vm.picUrl = url.substring((url.lastIndexOf("\/") + 1), url.length);
        },
        addDevLeaveApply: function () {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            var rowDatas = getSelectedRowDatas("#jqGrid");
            //判断是否存在已闲置记录
            for (var i = 0; i < rowDatas.length; i++) {
                if (rowDatas[i].devStatus == '闲置' || rowDatas[i].devStatus == '闲置审核中') {
                    layer.alert("设备[" + rowDatas[i].devName + "]处于闲置或闲置审核中，无需重复申请！", {icon: 5});
                    return;
                }
            }
            vm.open(ids);
        },
        open: function (ids) {
            // 打开设备闲置申请页面
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 设备闲置申请',
                content: '../device/addDevLeave.html?ids=' + ids,
                area: ['750px', '450px'],
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getTableDatas();
                    //添加记录
                    Ajax.request({
                        url: '../devleaverecord/addApply',
                        params: JSON.stringify(res),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert("操作成功", function () {
                                vm.reload();
                                layer.closeAll();
                            });
                        }
                    });
                }
            });
        },
        check: function () { // 设备审核
            // 校验是否选中记录
            var selectedDeviceList = getSelectedRowDatas('#jqGrid');
            if (!selectedDeviceList || selectedDeviceList.length == 0) {
                iview.Message.error("请选择一条记录");
                return;
            }
            // 已审核的备件不允许重复审核
            vm.approveDeviceList = [];
            vm.approveParam = {
                approveDeviceIdList: [],
                status: '1',
                remark: ''
            }
            for (var i = 0; i < selectedDeviceList.length; i++) {
                if (selectedDeviceList[i].reserve4 == '已审核') {
                    alert('设备[' + selectedDeviceList[i].devName + ']已通过审核，请取消选中！');
                    return;
                }
                vm.approveDeviceList.push(selectedDeviceList[i].devName);
                vm.approveParam.approveDeviceIdList.push(selectedDeviceList[i].id);
            }
            openWindow({
                title: "设备审核",
                area: ['450px', '350px'],
                content: jQuery("#apply"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    Ajax.request({
                        url: '../deviceinfo/Approval',
                        params: JSON.stringify(vm.approveParam),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            layer.close(index);
                            alert('审核完毕', function (index) {
                                vm.reload();
                                vm.approveParam = {
                                    approveDeviceIdList: [],
                                    status: '1',
                                    remark: ''
                                };
                                // 清空列表
                                vm.approveDeviceList = [];
                            });
                        }
                    });
                }
            });
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        },
        handleBeforeUpload: function () {
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleSuccess2: function (res, file) {
            if (res.code == 0) {
                this.$Loading.finish();
                iview.Message.success('文件上传成功');
                alert(res.msg, function (index) {
                    vm.reload();
                });
            } else {
                this.$Loading.error();
                this.$Notice.error({
                    title: '导入失败',
                    desc: res.msg
                })
            }
        },
        handleError2: function (err, file) {
            alert('导入失败');
        },
    }
});
